#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年11月3日

@author: chenyongbing
'''


import sys,os

import datetime


current_dir = os.path.split(os.path.realpath(__file__))[0]
import numpy
sys.path.append(os.path.join(current_dir,'../'))
from base.PyMySQL import ConnectMySQL
from base.localConfig import baseLocalConfig
host = baseLocalConfig.mysqlConfig['datatuning']['host']
user = baseLocalConfig.mysqlConfig['datatuning']['user']
passwd = baseLocalConfig.mysqlConfig['datatuning']['passwd']
db = baseLocalConfig.mysqlConfig['datatuning']['db']


import logging



class SimilarFlow(object):
    '''
    classdocs
    '''


    def __init__(self,task_name=None):
        '''
        Constructor
        '''
        
        if task_name==None:task_name = 's_f_'+datetime.date.today().strftime('%Y-%m-%d')
        
        self.myConnectMySQL = ConnectMySQL(host=host, user=user, password=passwd, db=db)
    def get_2_list_percent(self,alist,blist):
        clist = []
        #print alist,blist
        if len(alist)!=len(blist):
            return 
        for i in range(len(alist)):
            a = alist[i]
            b = blist[i]
            if a==0:continue
            clist.append(abs((float(a)-float(b))/float(a)))
        return clist
    
    
    
    
    def similar_flow(self,group,group_name=None,real_data=[],rssiMsgs={},F=0.2,role_name='all_customer'):
        rMsgs = {}
        fdict = {}
        if group_name ==None:group_name = ''
        for rssi_walkby,blist in rssiMsgs.iteritems():  
            clist = self.get_2_list_percent(real_data, blist)
            if len(clist)==0:
                avg = 999
            else:
                avg = sum(clist)/float(len(clist))
            var = numpy.var(clist,ddof=1)
            if avg<=F:
                fdict[rssi_walkby] = {'avg':avg,'var':var}
        if len(fdict)==0:
            if role_name == 'all_customer':
                if group_name !=None:
                    rmsg =  u'门店%s(%s) 入店数据严重偏离，无法确认rssi'%(group_name,group)
                else:
                    rmsg =  u'门店 %s 入店数据严重偏离，无法确认rssi'%group
            elif role_name == 'all_flow':
                if group_name !=None:
                    rmsg =  u'门店%s(%s) 客流数据严重偏离，无法确认rssi'%(group_name,group)
                else:
                    rmsg =  u'门店 %s 客流数据严重偏离，无法确认rssi'%group
            else:
                if group_name!=None:
                    rmsg =  u'门店%s(%s) 数据严重偏离，无法确认rssi'%(group_name,group)
                else:
                    rmsg =  u'门店%s(%s) 数据严重偏离，无法确认rssi'%(group_name,group)
            logging.warning(rmsg)
            rMsgs['msg'] = rmsg
        else:
            fkeys = fdict.keys()
            expect_rssi_walkby =fkeys[0]
            expect_var = fdict[expect_rssi_walkby]['var']
            for fkey in fkeys:
                var = fdict[fkey]['var']
                if var < expect_var:
                    expect_rssi_walkby = fkey
                    expect_var = var
            expect_rssi = expect_rssi_walkby.split(',')[0]
            expect_walkby = expect_rssi_walkby.split(',')[1]
            if role_name == 'all_customer':
                rmsg = u'门店 %s(%s) 入店期望rssi:%s , 期望入店时长:%s'%(group_name,group,expect_rssi,expect_walkby)
                rMsgs['expect_rssi'] = expect_rssi
                rMsgs['expect_walkby'] = expect_walkby
            elif role_name == 'all_flow':
                rmsg = u'门店%s(%s) 客流期望rssi:%s'%(group_name,group,expect_rssi)
                rMsgs['expect_rssi'] = expect_rssi
                
            else:
                rmsg = u'门店%s(%s) 期望rssi:%s , 期望入店时长:%s'%(group_name,group,expect_rssi,expect_walkby)
                rMsgs['expect_rssi'] = expect_rssi
                rMsgs['expect_walkby'] = expect_walkby
            logging.info(rmsg)
            rMsgs['msg'] = rmsg
        return rMsgs
    
    
    def get_opening_hours(self,opening='00:00:00-23:59:59'):
        st_h = int(opening.split('-')[0][:2])
        et_h = int(opening.split('-')[1][:2])
        hours = []
        for hour in range(st_h,et_h)+[et_h]:
            hours.append(str(hour))
        
        return hours
    def get_rssi_msg_from_database(self,tab='group_count_by_rssi',group='',days=[],role_name='all_customer',walkby=60,expect_rssi=None,opening_time=None,count_type='0'):
        if count_type == '0':
            query = 'select day,rssi,sum(visit_cnt) from %s where dgroup="%s" and day in (%s)'%(tab,group,'"'+'","'.join(days)+'"')
        else:
            query = 'select day,rssi,sum(visit_dis_cnt) from %s where dgroup="%s" and day in (%s)'%(tab,group,'"'+'","'.join(days)+'"')
        if role_name == None:
            pass
        elif count_type=='0':
            query = query + ' and role_name="%s" '%role_name
        else:
            query = query + ' and role_name="day_customer" '
        
        if role_name == 'all_customer':
            query = query + ' and walkby="%s"'%walkby
        if expect_rssi!=None:
            query = query + ' and rssi="%s"'%expect_rssi
        if opening_time!=None and opening_time.keys() == ['opening_weekday','opening_weekend'] and count_type=='0':
            opening_weekday = opening_time['opening_weekday']
            opening_weekend = opening_time['opening_weekend']
            opening_weekday_hours = self.get_opening_hours(opening_weekday)
            opening_weekend_hours = self.get_opening_hours(opening_weekend)
            query_weekday = query + ' and weekday(day) in (0,1,2,3,4) and hour in (%s) group by day,rssi order by rssi,day'%(','.join(opening_weekday_hours))
            query_weekend = query + ' and weekday(day) in (5,6) and hour in (%s) group by day,rssi order by rssi,day'%(','.join(opening_weekend_hours))
            logging.debug(query_weekday)
            logging.debug(query_weekend)
            print 'weekend',query_weekday
            ret = list(self.myConnectMySQL.SelectAll(query_weekday)) + list(self.myConnectMySQL.SelectAll(query_weekend))
        else:
            query = query + ' group by day,rssi order by rssi,day'
            logging.debug(query)
            ret = self.myConnectMySQL.SelectAll(query)
            print query
        datas = {}
        for date,rssi,visit_cnt in ret:
            dayStr = date.strftime('%Y-%m-%d')
            rssi = int(rssi)
            visit_cnt = int(visit_cnt)
            if rssi not in datas.keys():
                datas[rssi] = {}
                for day in days:
                    datas[rssi][day] = 0
            datas[rssi][dayStr] = visit_cnt
        if expect_rssi!=None:
            return datas[rssi]
        return datas
    
    def merger_rssi_data(self,alldatas={},rdatas=None,role_name='all_customer',walkby=None):
        for rssi , dayMsg in rdatas.iteritems():
            for day,count in dayMsg.iteritems():
                if day not in alldatas.keys():
                    alldatas[day] = {}
                if rssi not in alldatas[day].keys():
                    alldatas[day][rssi] = {role_name:{}}
                
                if walkby!=None:
                    
                    alldatas[day][rssi][role_name][walkby]=count
                else:
                    alldatas[day][rssi][role_name]=count
        return alldatas
                    
    def get_all_rssi_data(self,tab='group_count_by_rssi',group='',days=[],walkby_time_list=[15,30,45,60,120],opening_time=None,count_type='0'):
        datas = {}
        for role_name in ['all_customer']:
            if role_name == 'all_customer':
                for walkby in walkby_time_list:
                    walkby = int(walkby)
                    rdatas = self.get_rssi_msg_from_database(tab=tab, group=group, days=days, role_name=role_name, walkby=walkby, opening_time=opening_time,count_type=count_type)
                    datas = self.merger_rssi_data(alldatas=datas, rdatas=rdatas, role_name=role_name, walkby=walkby)
            else:
                rdatas = self.get_rssi_msg_from_database(tab=tab, group=group, days=days, role_name=role_name, walkby=None, opening_time=opening_time,count_type=count_type)
                datas = self.merger_rssi_data(alldatas=datas, rdatas=rdatas, role_name=role_name, walkby=None)
        ndatas = []
        for key,value in datas.iteritems():
            ndatas.append({'day':key,'data':value})
        return ndatas
                    
    def get_data_order_by_key(self,rdict={}):
        data = []
        keys = rdict.keys()
        keys.sort()
        for key in keys:
            data.append(int(rdict[key]))
        return data
    
      
    
    
    
    def run_similar_flow(self,group,group_name=None,real_customer=None,real_flow=None,walkby_time_list=[1,2],F=0.2,opening_time=None):     
        if real_customer!=None and len(real_customer)!=0:
            days = real_customer.keys()
            real_data = self.get_data_order_by_key(real_customer)
            role_name = 'all_customer'
        elif real_flow!=None and len(real_flow)!=0:
            days = real_flow.keys()
            real_data = self.get_data_order_by_key(real_flow)
            role_name = 'all_flow'
        else:
            return {'msg':u'输入的数据不能构成样本数据，请重新输入'}
        ndatas = {}
        if role_name == 'all_customer':
            for walkby in walkby_time_list:
                print group,days,role_name,walkby
                datas = self.get_rssi_msg_from_database(group=group, days=days, role_name=role_name, walkby=int(walkby)*60, opening_time=opening_time)
                
                for rssi,data in datas.iteritems():
                    ndata = self.get_data_order_by_key(data)
                    ndatas['%s,%s'%(rssi,walkby)] = ndata
        else:
            walkby = 60
            datas = self.get_rssi_msg_from_database(group=group, days=days, role_name=role_name, walkby=60, opening_time=opening_time)
            
            for rssi,data in datas.iteritems():
                ndata = self.get_data_order_by_key(data)
                ndatas['%s,%s'%(rssi,walkby)] = ndata            
        retMsg = self.similar_flow(group=group,group_name=group_name, real_data=real_data, rssiMsgs=ndatas, F=F,role_name=role_name)
        return retMsg
    
if __name__ == '__main__':
    mySimilarFlow = SimilarFlow()
   
    #clist= mySimilarFlow.get_2_list_percent(a0, a_60)
    
    F = 0.4
    opening_time = None
    group = '32010134'
    #opening_time = {'opening_weekday':'00:00:00-23:59:59','opening_weekend':'00:00:00-23:59:59'}
    #real_customer =  mySimilarFlow.get_rssi_msg_from_database(group=group, days=['2014-10-09','2014-10-08'],role_name="all_customer",walkby=60,opening_time=opening_time)
    #print real_customer
    #print mySimilarFlow.run_similar_flow(group,real_customer={'2014-10-08':200,'2014-10-09':200},walkby_time_list=[1,2],F=F,opening_time=opening_time)      
#     
    group = 32010406

    real_customer = {u'2014-09-20': u'68', u'2014-09-21': u'12', u'2014-09-22': u'24', u'2014-09-19': u'35', u'2014-09-18': u'26', u'2014-09-15': u'25', u'2014-09-14': u'54', u'2014-09-17': u'56', u'2014-09-16': u'45', u'2014-09-13': u'42', u'2014-09-12': u'30'}
    
    
    real_flow = {u'2014-09-29': u'1'}
    walkby_time_list = [u'1', u'2']
    F = 1
    opening_time = {'opening_weekday': u'00:00:00-23:59:59', 'opening_weekend': u'00:00:00-23:59:59'}
    
    ret = mySimilarFlow.run_similar_flow(group,real_customer=real_customer,walkby_time_list=[1,2],F=F,opening_time=opening_time)  
    print ret['msg']
